const path = require('path')
const fs = require('fs')
const util = require('../utils/util')
const imagemin = require('../utils/imagemin')
const qs = require('querystring')

const UserModule = require('../modules/user')
const jwt = require('../utils/jwt')

class UserInfoController {
  /**
   * 获取用户信息
   * 
   * @param ctx 
   */
  static async getUserInfo(ctx) {
    let req = qs.parse(ctx.request.url.split('?')[1])
    let tokenInfo
    if (req.token) {
      tokenInfo = jwt.verifyToken(req.token)
      req.name = tokenInfo.name
    }
    if (!(req.name || req.email)) {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
      return
    }
    try {
      let userInfo = []
      let userInfoByName = []
      let userInfoByEmail = []
      let adminInfoByName = []
      req.name && (userInfoByName = await UserModule.getUserByName(req.name))
      req.token && (adminInfoByName = await UserModule.getAdminByName(req.name))
      req.email && (userInfoByEmail = await UserModule.getUserByEmail(req.email))
      if (userInfoByEmail.length && userInfoByName.length && userInfoByName[0].name != userInfoByEmail[0].name) {
        ctx.body = {
          code: 416,
          msg: '请确认name与email属同一用户'
        }
        return
      } else {
        userInfoByEmail.length && (userInfo = userInfoByEmail)
        userInfoByName.length && (userInfo = userInfoByName)
        adminInfoByName.length && (userInfo = adminInfoByName)
      }
      if (!userInfo) {
        ctx.body = {
          code: 400,
          msg: '查无此人'
        }
        return
      }
      ctx.body = {
        code: 200,
        msg: 'success',
        data: userInfo[0]
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err
      }
    }
  }

  /**
   * 获取角色列表
   * 
   * @param {*} ctx {roles} 
   */
  static async getRolesList(ctx) {
    const req = qs.parse(ctx.request.url.split('?')[1])
    let list
    if (req.roles) {
      try {
        list = await UserModule.getUserByRoles(req.roles)
        ctx.body = {
          code: 200,
          data: list
        }
      } catch(err) {
        console.log(err)
        ctx.body = {
          code: 400,
          msg: err.stack
        }
      }
    } else {
      ctx.body = {
        code: 416,
        msg: '缺少参数'
      }
    }
  }

  /**
   * 获取用户列表
   * @param {*} ctx 
   */
  static async getUserList(ctx) {
    const req = qs.parse(ctx.request.url.split('?')[1])
    let where = {}
    const total = req.total
    const pagination = req.pagination
    if (req.name) {
      where.name = req.name
    }
    if (req.email) {
      where.email = req.email
    }
    if (req.roles) {
      where.roles = req.roles
    }
    try {
      let maxPagination = Math.ceil((await UserModule.getAllUserList({ where })).length)
      const list = await UserModule.getUserList({ where, total, pagination })
      ctx.body = {
        code: 200,
        data: {
          list,
          total: maxPagination
        },
      }
    } catch(err) {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: err.stack
      }
    }
  }

  /**
   * 更新用户信息
   * 
   * @param {*} ctx 
   */
  static async save(ctx) {
    const req = ctx.request.body
    if (!req.name) {
      ctx.body = {
        code: 416,
        msg: '缺少name'
      }
      return
    }

    if (!req.email && !req.password) {
      ctx.body = {
        code: 416,
        msg: '缺少必要参数'
      }
      return
    }
    
    try {
      const info = await UserModule.updateUserInfo(req.name, req.password, req.email)
      ctx.body = {
        code: 200,
        data: info
      }
    } catch(err) {
      ctx.body = {
        code: 400,
        msg: '' + err
      }
    }
  }

  
  /**
   * 用户头像上传
   * 
   * @param ctx
   * 
   */
  static async uploadAvatar(ctx) {
    const req = ctx.request

    // 过滤请求
    if (!ctx.request.files) {
      ctx.body = {
        code: 416,
        msg: '请上传图片'
      }
      return
    }

    const image = path.basename(req.files.image.path)

    const ext = image.split('.')
    if (!['jpg', 'png'].includes(ext[ext.length - 1])) {
      ctx.body = {
        code: 416,
        msg: '不支持此格式'
      }
      return
    }

    if (!req.body.name) {
      ctx.body = {
        code: 416,
        msg: '缺少name'
      }
      return
    }

    const targetDir = './public/images/avatar'
    util.isDirExists(targetDir)

    await imagemin.imageminComp(`./public/uploads/${image}`, `./public/images/avatar/${req.body.name}`)
    const currentImage = image.split('.')[0] + '.webp'
    const url = `${ctx.origin}/images/avatar/${req.body.name}/${currentImage}`
    
    const user = await UserModule.uploadAvatarURL(req.body.name, url)

    // 判断头像是否加载到avatar目录
    function imageExists() {
      return new Promise(res => {
        let hasImage = setInterval(() => {
          fs.stat(`./public/images/avatar/${req.body.name}/${currentImage}`, (err, stats) => {
            try {
              if (stats.isFile()) {
                res()
                clearInterval(hasImage)
              }
            } catch (err) {
              console.log(err)
            }
          })
        }, 500)
      })
    }

    await imageExists()
    ctx.body = {
      code: 200,
      msg: 'success',
      url: user.avatarURL
    }
  }
}

module.exports = UserInfoController
